package lizhe.dummynode;

public class AddTwoNumbers {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode();
        ListNode tmp = res;
        int carry = 0;
        while (l1 != null || l2 != null) {

            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;

            int val = x + y + carry;
            carry = val / 10;
            res.next = new ListNode(val % 10);

            if (l1 != null)
                l1 = l1.next;
            if (l2 != null)
                l2 = l2.next;
            res = res.next;
        }

        if (carry == 1) {
            res.next = new ListNode(1);
        }

        return tmp.next;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(9);
        ListNode l11 = new ListNode();
        l11.next = l1;
        for (int i = 0; i < 7; i++) {
            l1.next = new ListNode(9);
            l1 = l1.next;
        }

        ListNode l2 = new ListNode(9);
        ListNode l22 = new ListNode();
        l22.next = l2;
        for (int i = 0; i < 4; i++) {
            l2.next = new ListNode(9);
            l2 = l2.next;
        }

        ListNode listNode = addTwoNumbers(l11.next, l22.next);
        System.out.println("");
    }
}
